package com.ruoyi.web.controller.trackApply;


import cn.hutool.core.collection.CollUtil;
import cn.hutool.core.util.StrUtil;
import com.alibaba.druid.pool.DruidDataSource;
import com.ruoyi.common.core.domain.AjaxResult;
import com.ruoyi.common.core.domain.R;
import com.ruoyi.common.utils.biz.ResultSaveModule;
import com.ruoyi.common.utils.file.FileUtils;
import com.ruoyi.dm.mapper.DataCollectionMapper;
import com.ruoyi.framework.datasource.DynamicDataSource;
import com.ruoyi.trackapply.CloseEarthService;
import com.ruoyi.trackapply.domain.CloseEarthParam;
import com.ruoyi.trackapply.domain.CloseEarthVO;
import com.ruoyi.web.vo.MannedSpaceAssessVo;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.MediaType;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletResponse;
import java.io.File;
import java.sql.Connection;
import java.util.List;
import java.util.Map;
import java.util.TreeMap;
import java.util.stream.Collectors;


@RestController
@RequestMapping("/orbit/close")
@Slf4j
@Api(tags = "典型轨道大气应用-近地-深空航天器轨道大气模型评估")
public class CloseEarthController {

    @Autowired
    private CloseEarthService closeEarthService;


    @Autowired
    private MannedSpaceAssessController spaceAssess;

    @Autowired
    private DynamicDataSource dataSource;

    @Autowired
    private DataCollectionMapper dataCollectionMapper;


    @ApiOperation("评估(弃用)")
    @PostMapping("/estimate")
    public R<CloseEarthVO> cal(@Validated @RequestBody CloseEarthParam param) throws Exception {
        CloseEarthVO vo = closeEarthService.estimate(param);
        return R.ok(vo);
    }


    @ApiOperation("结果入库(弃用)")
    @PostMapping("/save")
    public R save(@Validated @RequestBody CloseEarthParam param) {
        closeEarthService.save(param);
        return R.ok();
    }

    @ApiOperation("结果下载(弃用)")
    @PostMapping("/download")
    public void download(@Validated @RequestBody CloseEarthParam param, HttpServletResponse response) {
        File file = closeEarthService.download(param);
        try {
            response.setContentType(MediaType.APPLICATION_OCTET_STREAM_VALUE);
            FileUtils.setAttachmentResponseHeader(response, file.getName());
            FileUtils.writeBytes(file.getAbsolutePath(), response.getOutputStream());
        }catch (Exception e) {
            log.error("下载失败",e);
        }
    }


    @PostMapping("/assess")
    @ApiOperation(value = "评估", notes = "根据页面输入条件评估出结果", httpMethod = "POST")
    public AjaxResult assess(@RequestBody MannedSpaceAssessVo vo) {
        //同 载人航天器
        return spaceAssess.assess(vo);
    }

    @PostMapping("/correct")
    @ApiOperation(value = "修正", notes = "根据页面输入条件得出修正结果", httpMethod = "POST")
    public AjaxResult magneticPredict(@RequestBody MannedSpaceAssessVo vo) {

        //同 载人航天器
        AjaxResult result = spaceAssess.magneticPredict(vo);
        Map<String,Object> resultMap =(Map) result.get("data");
        resultMap.put("module", ResultSaveModule.TRACK_APPLY);
        resultMap.put("submodule", ResultSaveModule.TRACK_APPLY_DEEP);
        return result;
    }

    @PostMapping("/forecast")
    @ApiOperation(value = "预报", notes = "根据页面输入条件得出预报结果", httpMethod = "POST")
    public AjaxResult magneticForecast(@RequestBody MannedSpaceAssessVo vo) {
        //同 载人航天器
        return spaceAssess.magneticForecast(vo);
    }


    @GetMapping("/spacecraft")
    @ApiOperation(value = "获取载人航天器列表", notes = "获取载人航天器列表", httpMethod = "GET")
    public AjaxResult getSpacecraftList() throws Exception{

        String schemaName ;
        Connection connection = null;
        try{
            connection = dataSource.getConnection();
            String schema = connection.getSchema();
            if (StrUtil.isNotBlank(schema)){
                schemaName = schema;
            }else {
                schemaName = connection.getMetaData().getUserName();
            }
            List<String> tableNames = dataCollectionMapper.selectAllTableNames(schemaName.toLowerCase()); //大写最好
            if (CollUtil.isEmpty(tableNames)){
                return AjaxResult.error("模式: {} 下没有找到任何数据库表");
            }
            List<String> finalTables = tableNames
                    .stream()
                    .map(String::toUpperCase)
                    .filter(name -> name.contains("SWDATA_OBS_DEN_"))
                    .filter(name -> !name.contains("GRACEA_SZ2")
                            && !name.contains("GRACEA_GRACEB")
                            && !name.contains("_FUSION")
                    )
                    .collect(Collectors.toList());

            if (CollUtil.isEmpty(finalTables)){
                return AjaxResult.error("模式: {} 下没有找到任何符合搜索条件的数据库表");
            }
            Map<String, String> resultMap = finalTables.stream()
                    .map(o -> o.replace("SWDATA_OBS_DEN_", ""))
                    .collect(TreeMap::new, (map,data) -> {
                        map.put(data,data);
                    }, TreeMap::putAll);
            return AjaxResult.success(resultMap);
        }catch (Exception e){
            e.printStackTrace();
            return AjaxResult.error(e.getMessage());
        }finally {
            if (connection!=null){
                connection.close();
            }
        }

    }
}
